<?php
/**
 * 管理控制器基本类
 */
class Sy_ControllerBase extends \Yaf\Controller_Abstract {
	public $user;
	public $is_admin;
	/**
	 * 检查登录
	 * @access public
	 */
	public function checkLogin($is_return = FALSE) {
		$token = $_COOKIE['ea_token'];
		$tverify = $_COOKIE['ea_tverify'];
		$valid = FALSE;
		if (!empty($token) && !empty($tverify)) {
			$et = Sy_Utils::ea()->call('user.token', [
				'token' => $token,
				'tverify' => $tverify,
				'user' => 1
			]);
			if ($et['is_valid']) {
				$this->user = $et['user'];
				$valid = TRUE;
				$is_admin = strpos(\Yaf\Registry::get('config')->application->admin, $this->user['id'] . ',') !== FALSE;
			}
		}
		if (!$valid) {
			if ($is_return) {
				return FALSE;
			} else {
				$this->message('您需要登录才能查看此页面');
				exit;
			}
		} else {
			return TRUE;
		}
	}
	/**
	 * 返回JSON结果
	 * @access public
	 * @param mixed $result
	 * @param int $code 代码
	 * @param string $error 错误信息
	 */
	public function json($result = NULL, $code = 200, $error = '') {
		if ($result === NULL) {
			echo json_encode(['code' => $code, 'error' => $error]);
		} else {
			echo json_encode(['code' => $code, 'data' => $result]);
		}
		exit;
	}
	/**
	 * Assign简化
	 * @access protected
	 * @param string $key
	 * @param mixed $value
	 */
	protected function assign($key, $value) {
		$this->getView()->assign($key, $value);
	}
	/**
	 * 显示提示页面
	 * @access public
	 * @param string $msg
	 * @param string $url 重定向到
	 * @param int $type 页面类型，错误页面或成功页面
	 */
	public function message($msg, $url = '', $type = 1) {
		$this->assign('message', $msg);
		if (!empty($url) && $url[0] === '/') {
			$url = \Yaf\Registry::get("urlPrefix") . substr($url, 1);
		}
		$this->assign('url', $url);
		$this->display('common/' . $type === 1 ? 'success' : 'error');
	}
	/**
	 * 静默跳转
	 * @access public
	 * @param string $url
	 */
	public function R($url) {
		$this->redirect(\Yaf\Registry::get("urlPrefix") . $url);
	}
}